﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;


namespace WorkTool.Controls
{
	public partial class Db2QuerierTabObject : UserControl
	{
		private DataAccess dataAccess;
		public string ConnectionString { set; private get; }

		public Db2QuerierTabObject(string ConnectionString)
		{
			dataAccess = new DataAccess(ConnectionString);
			InitializeComponent();
			txtQuery.Focus();
		}
		public Db2QuerierTabObject() {
			InitializeComponent();
		}
		/// <summary>Executes the query in the textbox. Executes selected portion only if applicable.</summary>
		public void Execute()
		{
			if (dataAccess == null && !string.IsNullOrEmpty(ConnectionString))
				dataAccess = new DataAccess(ConnectionString);
			else if (dataAccess == null)
				HandleException(new ApplicationException("ConnectionString is null"));
			if (string.IsNullOrEmpty(txtQuery.Text))
				HandleException(new ApplicationException("Cannot execute empty query"));
			try
			{
				DataTable dt = dataAccess.ReturnDB2(
					string.IsNullOrEmpty(txtQuery.SelectedText)
					? txtQuery.Text
					: txtQuery.SelectedText
					);
				dgvResults.DataSource = dt;
			}
			catch (Exception ex)
			{
				HandleException(ex);
			}
		}


		public void HandleException(Exception ex)
		{
			DataTable dt = new DataTable();
			dt.Columns.Clear();
			dt.Columns.Add(new DataColumn("Error", "".GetType()));
			dt.Columns.Add(new DataColumn("Detail", "".GetType()));
			DataRow dr = dt.NewRow();
			dr["Error"] = ex.Message;
			dr["Detail"] = ex.ToString();
			dt.Rows.Add(dr);
			dgvResults.DataSource = dt;
		}
	}
}
